package com.redsoft.epip.handler;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.redsoft.epip.builder.TextBuilder;
import com.redsoft.epip.entity.Member;
import com.redsoft.epip.service.MemberService;
import com.youzan.open.sdk.util.json.JsonUtils;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class SubscribeHandler extends AbstractHandler {

//	@Autowired
//	private ScoreRecordService scoreRecordService;

	@Autowired
	private MemberService memberService;

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
			Map<String, Object> context, WxMpService weixinService,
			WxSessionManager sessionManager) throws WxErrorException {

		this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());
		System.out.println("============>关注微信事件：" + JsonUtils.toJson(wxMessage));

		// 获取微信用户基本信息
		WxMpUser userWxInfo = weixinService.getUserService()
				.userInfo(wxMessage.getFromUser(), null);

		if (userWxInfo != null) {
			userWxInfo.setSubscribeTime(null);
			Member member = memberService.findByOpenId(userWxInfo.getOpenId());
			/*
			 * member 为空，说明该用户没有注册。
			 * 执行:
			 * 	1.保存到会员信息表里  
			 * 	2.如果带参数说明是好友扫描过来的，该好友增加积分记录
			 */
			if (member == null) {
				System.out.println("============>该用户不在系统中，是新用户！");
				try {
					Member memberTmp = new Gson().fromJson(new Gson().toJson(userWxInfo), Member.class);
					// member.setId(member.getOpenId());

					String eventKey = wxMessage.getEventKey();
					if (!"".equals(eventKey) && eventKey != null) {//不为空代表是扫描的带参数事件
						//获取参数实际值，qrscene_为前缀
						String userId = eventKey.replaceAll("qrscene_", "");
						//推荐人id
						memberTmp.setReferee(userId);
						
						//处理参数
						handleParamsEvent(userId);
					}
					
					member = memberService.save(memberTmp);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("============>该用户在系统中已存在，不是新用户！");
			}
		}

		WxMpXmlOutMessage responseResult = null;
		try {
			responseResult = handleSpecial(wxMessage);
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
		}

		if (responseResult != null) {
			return responseResult;
		}

		try {
			return new TextBuilder().build("感谢关注", wxMessage, weixinService);
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
		}

		return null;
	}

	/**
	 * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
	 */
	private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
			throws Exception {
		//TODO
		return null;
	}

	/**
	 * 
	 * 处理关注带参数事件，扫码
	 * <pre>
	 * 处理关注带参数事件，扫码
	 * </pre>
	 * 
	 * @author lixiaodong
	 * @param wxMessage
	 */
	private void handleParamsEvent(String eventKey) {
//		if (!"".equals(eventKey) && eventKey != null) {//不为空代表是扫描的带参数事件
//
//			ScoreRecord record = new ScoreRecord();
//
//			record.setDirection(0);
//			record.setUserId(eventKey);
//			try {
//				//         		System.out.println("============>新增积分");
//				scoreRecordService.save(record);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
	}

}
